package com.liyunc.demo.base.component;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JProgressBarExample {

    private static final int MIN_PROGRESS = 0;
    private static final int MAX_PROGRESS = 100;

    private static int currentProgress = MIN_PROGRESS;

    public static void main(String[] args) {
        JFrame jf = new JFrame("测试窗口");
        jf.setSize(250, 250);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();

        //创建一个进度条
        JProgressBar jProgressBar = new JProgressBar();

        //设置最大值和最小值
        jProgressBar.setMinimum(MIN_PROGRESS);
        jProgressBar.setMaximum(MAX_PROGRESS);

        //设置当前进度
        jProgressBar.setValue(currentProgress);

        //绘制百分比
        jProgressBar.setStringPainted(true);

        //添加进度改变监听器
        jProgressBar.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                System.out.println("当前进度值: " + jProgressBar.getValue() + "; " +
                        "进度百分比: " + jProgressBar.getPercentComplete());
            }
        });

        // 添加到内容面板
        panel.add(jProgressBar);

        jf.setContentPane(panel);
        jf.setVisible(true);

        // 模拟延时操作进度, 每隔 0.5 秒更新进度
        new Timer(20, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentProgress++;
                if (currentProgress > MAX_PROGRESS) {
                    ((Timer) e.getSource()).stop();
                    //currentProgress = MIN_PROGRESS;
                }
                jProgressBar.setValue(currentProgress);
            }
        }).start();
    }
}
